import React, { Component } from 'react';

import { connect } from 'react-redux';


// 导入actions
import { add_brand, del_brand, get_brands_async, del_brand_async,reset_current_brand } from '../redux/actions';

class List extends Component {
    constructor(props) {
        super(props);
        // 调用异步action,请求品牌列表数据
        this.props.get_brands_async();
    }
    del(id) {
        // 调用store对象的dispatch方法, 实现品牌删除
        if (window.confirm('确认删除?') === false) {
            return false;
        }
        // 通过异步action实现品牌删除
        this.props.del_brand_async(id);
    }
    // 获取当前要被编辑的品牌信息
    edit(item){
        this.props.reset_current_brand(item);
    }
    render() {
        return (
            <div>
                <table className="table table-bordered">
                    <thead>
                        <tr>
                            <th>品牌id</th>
                            <th>品牌名称</th>
                            <th>添加时间</th>
                            <th>操作</th>
                        </tr>
                    </thead>
                    <tbody>
                        {
                            this.props.list.map(item => (
                                <tr key={item.id}>
                                    <td>{item.id}</td>
                                    <td>{item.name}</td>
                                    <td>{item.ctime}</td>
                                    <td>
                                        <button className="btn btn-info" onClick={() => this.edit(item)}>编辑</button>
                                        <button className="btn btn-danger" onClick={() => this.del(item.id)}>删除</button>
                                    </td>

                                </tr>
                            ))
                        }
                    </tbody>
                </table>
            </div>
        );
    }
}

export default connect(
    (state) => ({ list: state.brands,brandCurrent:state.brandCurrent }),
    {
        add_brand, del_brand, get_brands_async, del_brand_async,reset_current_brand
    }
)(List);
